from flask import Blueprint,session,jsonify,request
from model import User,classInfo,course,statuscourse,UserInfo,db,messageInfo,uniquevalue
from model import redisclient,textvalue
from datetime import datetime
from datetime import timedelta
import requests
import json
import random
def gettoken():
    try:
        url='https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=QGJAEnxZulAcU8le5ahk6vrj&client_secret=6vvyCj0U95FyrB7sxh64xkjv86sUPC0i'
        response=requests.post(url=url,json={})
        token=response.json()['access_token']
        return 200,token
    except Exception:
        return 400,''
    
code,token = gettoken()
def getchat(messagedata):
    global token;
    if code!=200:
        return 400,'请求失败'
    try:
        
        url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token="+token
       
        payload = json.dumps({
            "messages": messagedata,
            "disable_search": False,
            "enable_citation": False
        })
        headers = {
            'Content-Type': 'application/json'
        }
    
        response = requests.request("POST", url, headers=headers, data=payload)
      
        return 200,response.json()['result']
    except Exception:
        return 400,''

user=Blueprint('user',__name__,url_prefix='/api/user')
@user.route('/course',methods=['GET','PUT'])
def getcourse():
    
    data = session.get('data')
    if data is None:
        return jsonify(code=400, message='请先登录')
    username = data['username']
    if request.method=='GET':
        finduser=User.query.filter_by(username=username).first()
        userid=finduser.id;
        findclass=classInfo.query.filter_by(userid=userid).first()
        classname=findclass.classname
        findclass=classInfo.query.filter_by(classname=classname,userid=None).first()
        if findclass is None:
            return jsonify(code=400,message='班级不存在')
        findcourselist=course.query.filter_by(classid=findclass.id).all()
    
        courseiddata=[]
        data=[]
        for h in findcourselist:
            courseiddata.append(h.id)
            gender=UserInfo.query.filter_by(username=h.teacher).first().gender
            data.append({"courseid":h.id,"coursename":h.coursename,'teacher':h.teacher,'gender':'男' if gender else '女','messages':h.messages})
        findstatus=statuscourse.query.filter(statuscourse.courseid.in_(courseiddata),statuscourse.username==username).all()
        
        index=0
        for j in data:
            j['status'] = False
            for status in findstatus:
                if j['courseid'] == status.courseid:
                    j['status'] = True
                    break
            data[index]=j
            index+=1
        return jsonify(code=200,data=data)
    elif request.method == 'PUT':
        
        data = request.get_json()
        courseid=data.get('courseid')
        if courseid == None:
          
            return jsonify(code=400,message='参数错误')
        findcourse=course.query.filter_by(id=courseid).first()
        if findcourse is None:
            return jsonify(code=400,message='课程不存在')
        findstat=statuscourse.query.filter_by(courseid=courseid,username=username)
        
        if findstat.first() == None:
          
            db.session.add(statuscourse(courseid=courseid,username=username))
            db.session.commit() 
        else:
           
            findstat.delete()
            db.session.commit()
        return {'code':200}
@user.route("/chat",methods=['POST','GET'])
def chatMessage():
  
    if session.get('data') is  None:
            return jsonify(code=400,message='请登录重试')
    username=session.get('data')['username']
    if request.method == 'POST':
        message=request.get_json().get('message')
        if message is None:
            return jsonify(code=400,message='请输入内容')
       
        messagedata=redisclient.get(username)
   
        if messagedata is not None:
            messagedata=eval(messagedata)
            messagedata.append({'role':'user','content':message,'timestamp':datetime.now().strftime('%Y-%m-%d %H:%M')})

        else:
            messagedata=[{'role':'user','content':message}]
        message1=message
        code,message=getchat(messagedata=messagedata)
        if code!=200:
            return jsonify(code=400,message='服务端模型异常')
        messagedata.append({'role':'assistant','content':message,'timestamp':datetime.now().strftime('%Y-%m-%d %H:%M')})
        redisclient.setex(username, timedelta(hours=3),value=f"{messagedata}")
        try:
            value=textvalue(message1)
        except Exception:
            value=random.randint(0,2)
        try:
            db.session.add(messageInfo(username=username,message=message1,chatmessage=message[:1000],value=value))
            db.session.commit()
        except Exception as e:
           print(str(e))
        return jsonify(code=200,message=message)
    elif request.method=='GET':
        findstr=redisclient.get(username)
        if findstr is None:
            return {'code':200,'messagedata':[]}
        return {'code':200,'messagedata':eval(findstr),'username':username}
@user.route('/getmessages')
def getmessages():
    data=[]
    for i in  messageInfo.query.all():
       data.append(i.value)
    return data
                    
@user.route('/uniquevalue',methods=['POST','GET'])
def adduniquevalue():
    sessiondata=session.get('data')
    if sessiondata is None:
        return jsonify(code=400,message='请先登录')
    username=sessiondata['username']
    user=User.query.filter_by(username=username).first()
    if user is None:
        return jsonify(code=400,message='用户不存在')
    userid=user.id
    print(userid)
    if request.method == 'POST':
        data=request.get_json()
        courseid=data.get('courseid')
        if courseid is None:
            return jsonify(code=400,message='参数错误')
       
        findunique=uniquevalue.query.filter_by(userid=userid,courseid=courseid,timestamp=datetime.now().strftime('%Y-%m-%d')).first()
        if findunique is None:
            db.session.add(uniquevalue(userid=userid,courseid=courseid,timestamp=datetime.now().strftime('%Y-%m-%d'),number=1))
            db.session.commit()
            return jsonify(code=200,message='添加成功')
        findunique.number =findunique.number+1
        db.session.commit()
        return jsonify(code=200,message='添加成功')
    elif request.method == 'GET':
        findcourse=statuscourse.query.filter_by(username=username).all()
        courseiddata=[]
        data=dict(iqdata=list(),coursedata=list(),code=200)

        for i in findcourse:
           courseiddata.append(i.courseid)
        for j in course.query.filter(course.id.in_(courseiddata)).all():
            for i in courseiddata:
                if i==j.id:
                    print(j.coursename)
                    data['coursedata'].append(j.coursename)
        for i in courseiddata:
            findiq= uniquevalue.query.filter_by(courseid=i,userid=userid,timestamp=datetime.now().strftime('%Y-%m-%d')).first()
            if findiq is None:
                data['iqdata'].append(0)
                continue
            data['iqdata'].append(findiq.number)
        return data
